﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using de.rwth.rz.campus.sputils.Security;

namespace de.rwth.rz.campus.sputils.ItemEventReceiverHelper
{
    /// <remarks>
    /// 
    /// Copyright 2010 RWTH Aachen, CAMPUS Labs
    /// 
    /// Licensed under the Apache License, Version 2.0 (the "License");
    /// you may not use this file except in compliance with the License.
    /// You may obtain a copy of the License at
    ///
    /// http://www.apache.org/licenses/LICENSE-2.0
    ///
    /// Unless required by applicable law or agreed to in writing, software
    /// distributed under the License is distributed on an "AS IS" BASIS,
    /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    /// See the License for the specific language governing permissions and
    /// limitations under the License.
    /// 
    /// This class can be used to send emails to SharePoint groups.
    /// For every SharePoint user in a SharePoint group an email is generated.
    /// Be aware of the load of your SMTP server.
    ///
    /// This class contains helper methods to handle list items
    /// </remarks>
    public class ItemEventReceiverHelper
    {
        /// <summary>
        /// Splits a SPItemEventDataCollection object into a list of strings
        /// </summary>
        /// <param name="afterProperties">The SPItemEventDataCollection object</param>
        /// <returns>A list of strings which contains the values of the SPItemEventDataCollection object</returns>
        /// <example>List<String> toValues = ItemEventReceiverHelper.GetValues(properties.AfterProperties["Value"]);</example>
        public static List<String> GetValues(Object afterProperties)
        {
            List<String> items = new List<String>();
            if (afterProperties != null)
            {
                if (!String.IsNullOrEmpty(afterProperties.ToString()))
                {
                    try
                    {
                        SPFieldMultiColumnValue helper = new SPFieldMultiColumnValue(afterProperties.ToString());
                        for (int i = 0; i < helper.Count; i++)
                        {
                            items.Add(helper[i]);
                        }
                    }
                    catch (ArgumentException)
                    {
                        //just ignore undocumented argument exception
                    }
                }
            }
            return items;
        }

        /// <summary>
        /// Splits a semicola separated textfield.
        /// </summary>
        /// <param name="afterProperties">The semicola separated entries</param>
        /// <returns>A list of entries</returns>
        public static List<String> GetOthers(Object afterProperties)
        {
            List<String> others = new List<String>();
            if (afterProperties != null)
            {
                if (!String.IsNullOrEmpty(afterProperties.ToString()))
                {
                    String trimmedString = afterProperties.ToString().Replace(" ", String.Empty);
                    String[] items = trimmedString.Split(';');
                    foreach (String item in items)
                    {
                        if (!String.IsNullOrEmpty(item)) others.Add(item);
                    }
                }
            }
            return others;
        }

        /// <summary>
        /// This method sets the permissions for a list elevateditem.
        /// </summary>
        /// <param name="item">The list elevateditem for which the permission should be set</param>
        /// <param name="groups">The list of groups that get read permission</param>
        /// <param name="user">The user that get read and delete permissions</param>
        public static void SetListItemPermissions(SPListItem item, List<SPGroup> groups, SPUser user)
        {
            using (SPSite siteCollection = SPSiteSecurity.GetElevatedSite(item.Web.Site))
            {
                using (SPWeb webSite = siteCollection.OpenWeb(item.Web.ID))
                {
                    SPListItemCollection lic = webSite.Lists[item.ParentList.ID].Items;
                    SPListItem elevatedItem = webSite.Lists[item.ParentList.ID].Items[item.UniqueId];
                    //Remove all permissions
                    if (elevatedItem.HasUniqueRoleAssignments)
                    {
                        elevatedItem.ResetRoleInheritance();
                        elevatedItem.BreakRoleInheritance(false);
                        if (elevatedItem.RoleAssignments.Count > 0)
                            foreach (SPRoleAssignment assignment in elevatedItem.RoleAssignments)
                            {
                                assignment.RoleDefinitionBindings.RemoveAll();
                                assignment.Update();
                            }
                    }
                    else
                    {
                        elevatedItem.BreakRoleInheritance(false);
                    }
                    //Give groups read permission
                    foreach (SPGroup group in groups)
                    {
                        SPRoleAssignment groupRoleAssignment = new SPRoleAssignment(group);

                        SPRoleDefinition groupRoleDefinition = webSite.RoleDefinitions.GetByType(SPRoleType.Reader);
                        groupRoleAssignment.RoleDefinitionBindings.Add(groupRoleDefinition);
                        elevatedItem.RoleAssignments.Add(groupRoleAssignment);
                    }
                    //Give user delete permission
                    SPRoleAssignment userRoleAssignment = new SPRoleAssignment(user);
                    SPRoleDefinition userRoleDefinition = webSite.RoleDefinitions.GetByType(SPRoleType.Administrator);
                    userRoleAssignment.RoleDefinitionBindings.Add(userRoleDefinition);
                    elevatedItem.RoleAssignments.Add(userRoleAssignment);
                    //Owner has admin rights
                    if (webSite.AssociatedOwnerGroup != null)
                    {
                        SPRoleAssignment ownerRoleAssignment = new SPRoleAssignment(webSite.AssociatedOwnerGroup);
                        SPRoleDefinition ownerRoleDefinition = webSite.RoleDefinitions.GetByType(SPRoleType.Administrator);
                        ownerRoleAssignment.RoleDefinitionBindings.Add(ownerRoleDefinition);
                        elevatedItem.RoleAssignments.Add(ownerRoleAssignment);
                    }
                    
                }
            }
        }
    }
}
